﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GosWeb.Models.Db;
using GosWeb.Biz;
using System.Text;
using GosWeb.Models.Form;

namespace GosWeb.Controllers
{
    public class BiontController : Controller
    {
        GosDBContext db = GosDBContext.GetInstance();
        BiontBiz bb = BiontBiz.GetInstance();

        public ActionResult Index()
        {
            var bionts = db.Bionts.OrderByDescending(m => m.CreateDate)
                .Take(500);
            //var bionts = from m in db.Bionts orderby m.CreateDate descending select m;
            return View( bionts);
        }

        public ActionResult Query()
        {
            return View();
        }

        public ActionResult CheckBlood(string bi1, string bi2)
        {
            var br = new BloodRelation();
            br.BiontID1 = bi1;
            br.BiontID2 = bi2;
            if (br.Biont1 == null)
            {
                ModelState.AddModelError("", string.Format("错误:{0} 不存在!", bi1));
            }
            if (br.Biont2 == null)
            {
                ModelState.AddModelError("", string.Format("错误:{0} 不存在!", bi2));
            }
            if (br.Biont1 == br.Biont2)
            {
                ModelState.AddModelError("", string.Format("错误:ID 重复了！", bi2));
            }
            return View(br);
        }

        /// <summary>
        /// judge which page should open
        /// </summary>
        /// <param name="id"></param>
        /// <param name="An2"></param>
        /// <returns></returns>
        public ActionResult Details(string id)
        {
            //if (id == null)
            //{
            //    id = Request.QueryString["id"];
            //}

            if (string.IsNullOrWhiteSpace(id) == false)
            {
                id = id.Trim();
            }
            var p = db.Bionts.Find(id);
            if (p == null)
            {
                string errorMsg = string.Format("没找到此个体相关资料（编号 = {0}）！请返回检查输入是否有错误?", id);
                return RedirectToAction("Show", "Error", new { ErrorString = errorMsg });
            }
            else
            {
                return View(p);
            }
        }

        public ActionResult SonDaughters(string id)
        {
            var bionts = (from m in db.Bionts where (m.MotherID == id || m.FatherID == id) select m).OrderByDescending(m => m.Birthday);
            //bionts.OrderByDescending();
            return View("SonDaughters", bionts.ToList());
        }


        private void CheckModelState(Biont newBiont)
        {
            Biont f = newBiont.GetFather();
            if (f == null)
            {
                //ModelState.AddModelError("FatherID", "父 没找到！");
                //return View(newBiont);
            }
            else if (f.Sex != 0)
            {
                ModelState.AddModelError("FatherID", "父 性别不对！");
            }

            var m = newBiont.GetMother();
            if (m == null)
            {
                //ModelState.AddModelError("MotherID", "母 没找到！");
                //return View(newBiont);
            }
            else if (m.Sex != 1)
            {
                ModelState.AddModelError("MotherID", "母 性别不对！");
            }

            if (newBiont.NestNumber <= 0 || newBiont.NestNumber > 50)
            {
                ModelState.AddModelError("NestNumber", "窝次太小或太大了！");
            }
        }

        public ActionResult Edit(string id)
        {
            var biont = db.Bionts.Find(id);
            if (biont == null)
            {
                var err = "ID 没找到!";
                return RedirectToAction("Index", "Error", err);
            }
            return View(biont);
        }

        [HttpPost]
        public ActionResult Edit(Biont model)
        {

            var biont = db.Bionts.Find(model.BiontID);
            CheckModelState(model);
            if (ModelState.IsValid == true)
            {
                try
                {
                    UpdateModel(biont);
                    db.SaveChanges();
                    return RedirectToAction("Details", new { id = model.BiontID });
                }
                catch (Exception)
                {
                    ModelState.AddModelError("", "Edit Failure, see inner exception");
                }
            }

            return View(model);

        }

        public ActionResult Delete(string id)
        {
            var movie = db.Bionts.Find(id);
            if (movie == null)
                return RedirectToAction("IndexN");
            return View(movie);
        }

        [HttpPost]
        public RedirectToRouteResult Delete(string id, FormCollection collection)
        {
            var grs = db.GeneRatios.Where(m => m.AnID == id);
            foreach (var item in grs)
            {
                db.GeneRatios.Remove(item);
            }

            var movie = db.Bionts.Find(id);
            db.Bionts.Remove(movie);
            db.SaveChanges();

            return RedirectToAction("Index");
        }

        /// <summary>
        /// return a li list
        /// </summary>
        /// <param name="BID"></param>
        /// <param name="layer"></param>
        /// <returns></returns>
        public string GetAncestorTree(string BID, int layer)
        {
            Biont bn = bb.FindBiont(BID);
            string s = bb.PedigreeTree(BID);
            return s;
        }

        /// <summary>
        /// return a printable tree
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult PrintAncestorTree(string id)
        {
            Biont bn = bb.FindBiont(id);

            return View(bn);
        }

        public ActionResult CopyIt(string id)
        {
            return RedirectToAction("Create", new { id = id });
        }

        
        //[Authorize]
        /// <summary>
        /// Clone an exist 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Create(string id)
        {
            Biont bnTo;
            //for copy it
            Biont bnFrom = bb.FindBiont(id);
            if (bnFrom == null)
            {
                bnTo = new Biont();
                bnTo.BiontID = id;
                //return View();
            }
            else
            {
                bnTo = bnFrom.Clone() as Biont;
            }
            return View(bnTo);
        }

        [HttpPost]
        public ActionResult Create(Biont newBiont)
        {
            newBiont.BiontID = newBiont.BiontID.Trim().ToUpper();
            if (bb.FindBiont(newBiont.BiontID) != null)
            {
                ModelState.AddModelError("BiontID", "ID重复了！");
            }
            if (string.IsNullOrWhiteSpace(newBiont.FatherID) == false)
            {
                newBiont.FatherID = newBiont.FatherID.Trim().ToUpper();
            }

            if (string.IsNullOrWhiteSpace(newBiont.MotherID) == false)
            {
                newBiont.MotherID = newBiont.MotherID.Trim().ToUpper();
            }
            if (!(newBiont.Sex == 0 || newBiont.Sex == 1))
            {
               ModelState.AddModelError("Sex", "性别必填！");
            }

            if (ModelState.IsValid)
            {
                newBiont.CreateDate = DateTime.Now;
                db.Bionts.Add(newBiont);
                db.SaveChanges();
                return RedirectToAction("Details", new { id = newBiont.BiontID });
            }
            else
            {
                return View(newBiont);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="bDate"></param>
        /// <param name="eDate"></param>
        /// <returns></returns>
        public ActionResult ComplexQuery(string id, DateTime bDate, DateTime eDate)
        {
            id = id.Trim().ToUpper();
            //if()
            eDate = eDate.AddDays(1);
            IQueryable<Biont> bs = db.Bionts
                .Where(m => (m.BiontID.Contains(id) && m.Birthday > bDate && m.Birthday < eDate))
                .Take(500);
            return View(bs);
        }
    }

    enum CreateBiontType:int
    {
        Clone,
        CopyID
    }
}
